package com.strongbj.iot.devices.amazondb.response.entity;

import java.util.ArrayList;
import java.util.List;

import com.strongbj.core.util.ByteUtil;


/**
 * 呼叫标签信息的工厂类
 * @author yuzhantao
 *
 */
public class CallLabelFactory implements IEntityFactory<List<CallLabelEntity>> {
	static final int LABEL_SIZE=5;			// 一个标签的尺寸
	static final int LABEL_OFFSET = 0;		// 标签数据的偏移地址
	static final int LABEL_ID_SIZE=4;		// 标签编号的长度
	@Override
	public List<CallLabelEntity> parse(byte[] datas) {
		List<CallLabelEntity> list = new ArrayList<>();
		for(int i=LABEL_OFFSET;i<datas.length-LABEL_SIZE;i+=LABEL_SIZE){
			byte[] labId = new byte[LABEL_ID_SIZE];
			System.arraycopy(datas, i, labId, 0, LABEL_ID_SIZE);
			
			boolean isLabelAllZero = true;  // 是否标签全零
			for(int j=0;j<labId.length;j++) {
				if(labId[j]!=0) {
					isLabelAllZero=false;
				}
			}
			if(isLabelAllZero) continue;   // 如果标签全零不处理
			
			CallLabelEntity lab = new CallLabelEntity();
			lab.setLabelId(this.byteLabelId2String(labId));
			switch(datas[i+LABEL_ID_SIZE]){
			case 0:
				lab.setCallState(ExecutionState.Fail);
				break;
			case 1:
				lab.setCallState(ExecutionState.Success);
				break;
			default:
				lab.setCallState(ExecutionState.Unknown);
				break;
			}
			list.add(lab);
		}
		return list;
	}

	private String byteLabelId2String(byte[] labId) {
		StringBuffer sb = new StringBuffer();
		for(int j = 0;j<labId.length;j++) {
			sb.append(ByteUtil.bytesToUbyte(labId, j)+".");
		}
		String labCode = sb.toString();
		return labCode.substring(0,labCode.length()-2);
	}
}
